package com.zenithmind.common.security;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * Feign请求拦截器
 * 用于在Feign客户端请求中添加认证令牌
 * 确保微服务间调用时，用户身份信息可以被正确传递
 */
@Slf4j
@Component
public class FeignTokenInterceptor {

    private static final String AUTHORIZATION_HEADER = "Authorization";
    private static final String BEARER_PREFIX = "Bearer ";
    private static final String TOKEN_ATTRIBUTE = "zenithmind.jwt.token";

    /**
     * 获取当前请求中的令牌
     * @return 认证令牌，如果不存在则返回null
     */
    public String getToken() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            log.debug("RequestContextHolder中无法获取请求属性");
            return null;
        }

        HttpServletRequest request = requestAttributes.getRequest();
        
        // 首先尝试从请求属性获取令牌
        String token = (String) request.getAttribute(TOKEN_ATTRIBUTE);
        if (token != null && !token.isEmpty()) {
            return token;
        }
        
        // 如果请求属性中没有令牌，尝试从请求头获取
        String authHeader = request.getHeader(AUTHORIZATION_HEADER);
        if (authHeader != null && authHeader.startsWith(BEARER_PREFIX)) {
            return authHeader.substring(BEARER_PREFIX.length());
        }
        
        return null;
    }
} 